package com.luom.fsp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.product.ProductAddRequest;
import com.luom.fsp.model.dto.product.ProductUpdateRequest;
import com.luom.fsp.model.dto.product.ProductQueryRequest;
import com.luom.fsp.model.entity.Product;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.ProductVO;
import com.luom.fsp.service.ProductService;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 商品接口
 *
*/
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Resource
    private ProductService productService;

    // region 增删改查

    /**
     * 创建商品 
     *
     * @param productAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addProduct(@RequestBody ProductAddRequest productAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(productAddRequest == null, ErrorCode.PARAMS_ERROR);
        Product product = new Product();
        BeanUtils.copyProperties(productAddRequest, product);
        // 数据校验
        productService.validProduct(product, true);
        // 写入数据库
        boolean result = productService.save(product);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newProductId = product.getId();
        return ResultUtils.success(newProductId);
    }

    /**
     * 删除商品 
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteProduct(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Product oldProduct = productService.getById(id);
        ThrowUtils.throwIf(oldProduct == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = productService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新商品 （仅管理员可用）
     *
     * @param productUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateProduct(@RequestBody ProductUpdateRequest productUpdateRequest) {
        if (productUpdateRequest == null || productUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = productService.updateProduct(productUpdateRequest);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取商品 （封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ProductVO> getProductVOById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Product product = productService.getById(id);
        ThrowUtils.throwIf(product == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(productService.getProductVO(product,true));
    }

    /**
     * 根据 id 获取商品 用户端
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo/user")
    public BaseResponse<ProductVO> getProductVOByIdUser(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Product product = productService.getById(id);
        ThrowUtils.throwIf(product == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(productService.getProductVO(product,false));
    }

    /**
     * 分页获取商品 列表（仅管理员可用）
     *
     * @param productQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Product>> listProductByPage(@RequestBody ProductQueryRequest productQueryRequest) {
        long current = productQueryRequest.getCurrent();
        long size = productQueryRequest.getPageSize();
        // 查询数据库
        Page<Product> productPage = productService.page(new Page<>(current, size),
                productService.getQueryWrapper(productQueryRequest,false));
        return ResultUtils.success(productPage);
    }

    /**
     * 分页获取商品 列表（封装类）
     *
     * @param productQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ProductVO>> listProductVOByPage(@RequestBody ProductQueryRequest productQueryRequest) {
        long current = productQueryRequest.getCurrent();
        long size = productQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 如果排序字段是 sales，走 Redis 排序逻辑
        Page<Product> productPage;
        if ("sales".equalsIgnoreCase(productQueryRequest.getSortField())) {
            productPage = productService.page(new Page<>(current, size),
                    productService.getQueryWrapper(productQueryRequest,true));
        } else {
            // 查询数据库
            productPage = productService.page(new Page<>(current, size),
                    productService.getQueryWrapper(productQueryRequest,false));
        }
        // 获取封装类
        return ResultUtils.success(productService.getProductVOPage(productPage));
    }

    /**
     * 查询商品
     */
//    @GetMapping("/search")
//    public BaseResponse<Page<ProductVO>> searchProduct(String searchText) {
//        if (searchText == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        return ResultUtils.success(productService.searchProduct(searchText));
//    }

    // endregion
}
